//
//  JXPrivacyPwdController.m
//  JiaoX
//
//  Created by yinqy on 15/1/22.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXPrivacyPwdController.h"
#import "JXNavigationController.h"
#import "JXLoginRegistCheckController.h"


#define BASE_NUM 1000

#define TEXTFIELD_WIDTH [DimensUtils getScaleX:45]

#define TITLE_FONT_SIZE [DimensUtils getScaleX:15]

@interface JXPrivacyPwdController ()<UITextFieldDelegate>
{
    UILabel *_titleLabel;
    
    NSMutableArray *_fieldArray;
    
    UITextField *_inputField;
    
    UIButton *_forgetBtn;
    
    int inputCount;//输入次数
    
    NSString *pwdStr;
    
    
    
}

@end

@implementation JXPrivacyPwdController

-(instancetype)initWithFromType:(int)fromType{
    self = [super init];
    if (self) {
        self.formType = fromType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"启动密码"];
    [self.view setBackgroundColor:JXGlobalColorBg];
    [_titleLabel setText:@"请输入数字密码"];
    //设置导航栏按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_back" highImageName:@"navigationbar_back_highlighted" target:self action:@selector(back)];
    inputCount = 1;
    
    [self initViews];
    
    if (self.formType == FROM_TYPE_SELFFRG_SET) {
        //设置密码
        [_titleLabel setText:@"请输入数字密码,设置后保护您的隐私"];
    }else if(self.formType == FROM_TYPE_SELFFRG_CLOSE){
        //关闭密码
        [_titleLabel setText:@"请输入数字密码"];
    }else{
        //从splah进来，
        [_titleLabel setText:@"请输入数字密码"];
        self.navigationItem.leftBarButtonItem = nil;
        _forgetBtn.hidden= NO;
    }
    
    
    
    
}


-(void)initViews{
    
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(JXPublicInset, [DimensUtils getScaleY:30]+NavHeight, JXScreenW-JXPublicInset*2, TITLE_FONT_SIZE)];
    [_titleLabel setFont:[UIFont systemFontOfSize:TITLE_FONT_SIZE]];
    [_titleLabel setTextColor:JXThemeColor];
    [_titleLabel setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:_titleLabel];
    
    _fieldArray = [NSMutableArray array];
    
    CGFloat w = JXScreenW/4;
    for (int i = 0; i < 4; i++) {
        UILabel *filed = [self getTextField:CGRectMake((w-TEXTFIELD_WIDTH)/2+w*i, CGRectGetMaxY(_titleLabel.frame)+[DimensUtils getScaleY:15], TEXTFIELD_WIDTH, TEXTFIELD_WIDTH)];
        filed.tag = i+1+BASE_NUM;
        [_fieldArray addObject:filed];
    }
    
    _inputField = [[UITextField alloc]initWithFrame:CGRectMake(JXPublicInset, 400, JXScreenW-JXPublicInset*2, 50)];
    [_inputField setKeyboardType:UIKeyboardTypeNumberPad];
    [self.view addSubview:_inputField];
    [_inputField becomeFirstResponder];
    [_inputField setDelegate:self];
    [_inputField setHidden:YES];
    [_inputField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _forgetBtn = [[UIButton alloc]init];
    NSString *text = @"忘记密码 重新登录";
    [_forgetBtn setTitle:text forState:UIControlStateNormal];
    [_forgetBtn.titleLabel setFont:[UIFont systemFontOfSize:[DimensUtils getScaleX:12]]];
    [_forgetBtn setTitleColor:JXColor(102, 102, 102) forState:UIControlStateNormal];
    CGSize titleSize = [text sizeWithFont:_forgetBtn.titleLabel.font];
    _forgetBtn.frame = CGRectMake(JXScreenW-JXPublicInset-titleSize.width, CGRectGetMaxY(((UIView *)[_fieldArray firstObject]).frame)+[DimensUtils getScaleY:15], titleSize.width, titleSize.height);
    [_forgetBtn addTarget:self action:@selector(forgetPwdDid) forControlEvents:UIControlEventTouchUpInside];
    [_forgetBtn setHidden:YES];
    [self.view addSubview:_forgetBtn];
}

/**
 *  忘记密码点击
 */
-(void)forgetPwdDid{
    JXLoginRegistCheckController *ctrl = [[JXLoginRegistCheckController alloc]init];
    JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:ctrl];
    AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    myDelegate.isClearPrivacyPwd = YES;
    [self presentViewController:nav animated:YES completion:nil];
}

-(UILabel *)getTextField:(CGRect)frame{
    UILabel *field = [[UILabel alloc]initWithFrame:frame];
    [field setUserInteractionEnabled:YES];
    [field setTextAlignment:NSTextAlignmentCenter];
    [field.layer setBorderColor:JXColor(204, 204, 204).CGColor];
    [field.layer setBorderWidth:1];
    [self.view addSubview:field];
    return field;
}

- (void)textFieldDidChange:(UITextField *)textField{
    NSString *str = textField.text;
    [self resetLabel];
    for(int i=0; i<str.length; i++){
        UILabel *label = _fieldArray[i];
        [label setText:@"●"];
    }
    if (str.length==4) {
        [self dealEndInput];
    }
}

-(void)dealEndInput{
    if (self.formType == FROM_TYPE_SELFFRG_SET) {
        if (inputCount==1) {
            pwdStr = _inputField.text;
            //重置密码，进行第2次输入，些次密码临时保存
            [self resetLabel];
            [_inputField setText:@""];
            inputCount = 2;
            [_titleLabel setText:@"请确认您的密码"];
        }else{
            //判断是否与第一次输入的是否一样
            if ([_inputField.text isEqualToString:pwdStr]) {
                //相等，设置密码完成
                [UserDefaultsHelper setObject:_inputField.text forKey:KEY_HAVE_PASSWORD];
                [self endInputPwd];
            }else{
                // 如果两次设置的不一样，那么弹出提示两次输入密码不一致，请重新输入
                [DialogUtils showTipsWithView:self.navigationController.view String:@"两次密码不一致\n请重新输入"];
                // 重置数据
                [self resetLabel];
                [_inputField setText:@""];
                pwdStr = @"";
                inputCount = 1;
                [_titleLabel setText:@"请输入密码"];
            }
        }
    }else if(self.formType == FROM_TYPE_SELFFRG_CLOSE){
        // 关闭密码
        NSString *oldPwd = [UserDefaultsHelper stringForKey:KEY_HAVE_PASSWORD];
        if ([oldPwd isEqualToString:_inputField.text]) {
            //代表关闭成功
            //清空保存的密码
            [UserDefaultsHelper setObject:nil forKey:KEY_HAVE_PASSWORD];
            //关闭此页面
            [self endInputPwd];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:@"密码错误"];
            [self resetLabel];
            [_inputField setText:@""];
        }
    }else if(self.formType == FROM_TYPE_SPLASH){
        // 从启动页来的，取出数据对比
        NSString *oldPwd = [UserDefaultsHelper stringForKey:KEY_HAVE_PASSWORD];
        if ([oldPwd isEqualToString:_inputField.text]) {
            // 密码正确
            [self endInputPwd];
        } else {
            // 密码不正确
            [DialogUtils showTipsWithView:self.navigationController.view String:@"密码错误"];
            [self resetLabel];
            [_inputField setText:@""];

        }
    }
}

/**
 *  处理密码输入完成之后
 */
-(void)endInputPwd{
    if([self.delegate respondsToSelector:@selector(endSetPwd)]){
        [_delegate endSetPwd];
    }
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

/**
 *  返回按钮
 */
-(void)back{
    [self dismissViewControllerAnimated:NO completion:^{
    }];
}


-(void)resetLabel{
    [_fieldArray makeObjectsPerformSelector:@selector(setText:) withObject:@""];
}

@end
